package com.xxp.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xxp.controller.request.UserPageRequest;
import com.xxp.entity.User;
import com.xxp.mapper.UserMapper;
import com.xxp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    //查询所有
    @Override
    public List<User> list() {
        List<User> users = userMapper.list();
        return users;
    }
    //分页
    @Override
    public Object page(UserPageRequest userPageRequest) {
        //分页：pom文件当中使用：pagehelper-spring-boot-starter
        //在需要分页的方法前后使用startPage和new PageInfo，然后就会对结果封装成一个分页的对象，然后返回前端，前端对分页的对象进行处理
        PageHelper.startPage(userPageRequest.getPageNum(),userPageRequest.getPageSize());
        List<User> users = userMapper.listByCondition(userPageRequest);
        //直接返回一个new pageInfo
        return new PageInfo<>(users);

    }
    //新增
    @Override
    public void save(User user) {
        Date date=new Date();
        user.setUsername(DateUtil.format(date,"yyyyMMdd")+ Math.abs(IdUtil.fastSimpleUUID().hashCode()) );
        userMapper.save(user);
    }

    @Override
    public User getById(Integer id) {
        User user=userMapper.getById(id);
        return user;
    }

    @Override
    public void update(User user) {
        user.setUpdatetime(new Date());
        userMapper.update(user);
    }

    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }
}
